package com.illtamer.infinite.collapsar.server;

import com.illtamer.infinite.collapsar.server.smtp.SMTPServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

// https://blog.csdn.net/Oliverfly1/article/details/121174334
// http://www.yunrelay.com/news/mailnews/57213013292.html
public class SMTPServer {

    private static final EventLoopGroup bossGroup = new NioEventLoopGroup();

    private static final EventLoopGroup workerGroup = new NioEventLoopGroup();

    private static ChannelFuture serverChannel;

    public static void start() {
        ServerBootstrap server = new ServerBootstrap();

        server.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128) // 最大连接数
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new DelimiterBasedFrameDecoder(512*1024, Delimiters.lineDelimiter()))
                                .addLast(new StringDecoder(CharsetUtil.UTF_8))
                                .addLast(new StringEncoder(CharsetUtil.UTF_8))
                                // TODO 多线程
                                .addLast(new SMTPServerHandler());
                    }
                });
        try {
            serverChannel = server.bind(25).sync();
            serverChannel.addListener((ChannelFutureListener) listener -> System.out.println("SMTP服务已启动"));
            serverChannel.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            shutdown();
            e.printStackTrace();
        }
    }

    public static void shutdown() {
        if (serverChannel != null) serverChannel.channel().close().syncUninterruptibly();
        if (!bossGroup.isShutdown()) bossGroup.shutdownGracefully();
        if (!workerGroup.isShutdown()) workerGroup.shutdownGracefully();
        System.out.println("SMTP服务已关闭");
    }

    public static void main(String[] args) {
        start();
    }

}
